package lysjmaster.base.auth.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.crypto.digest.BCrypt;
import lombok.extern.slf4j.Slf4j;
import lysjmaster.base.auth.domain.User;
import lysjmaster.base.auth.repository.RoleRepository;
import lysjmaster.base.auth.repository.UserRepository;
import lysjmaster.base.common.CommonConstant;
import lysjmaster.base.common.exception.BaseException;
import lysjmaster.base.common.jwt.JwtUtil;
import lysjmaster.base.common.spring.base.BaseRepository;
import lysjmaster.base.common.spring.base.BaseService;
import lysjmaster.base.common.validation.Validation;
import lysjmaster.base.common.validation.domain.BindingResult;
import lysjmaster.base.common.web.ParamUtil;
import lysjmaster.base.common.web.Resp;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Created by zk on 2019-12-04 14:28
 * @description
 */
@Slf4j
@Service
@Transactional
public class UserService implements BaseService<User> {

    @Resource
    private UserRepository userRepository;
    @Resource
    private RoleRepository roleRepository;

    @Override
    public BaseRepository<User> getRepository() {
        return userRepository;
    }

    public String login(String username, String password) {
        User user = userRepository.findByUsername(username);
        if (ParamUtil.isBlank(user)) {
            throw new BaseException(Resp.ResStatus.PARAM_ERROR, "用户名不存在");
        }
        if (user.getDelFlag().equals(CommonConstant.DEL_FLAG)) {
            throw new BaseException(Resp.ResStatus.PARAM_ERROR, "用户已被禁用");
        }
        if (!BCrypt.checkpw(password, user.getPassword())) {
            throw new BaseException(Resp.ResStatus.PARAM_ERROR, "密码错误");
        }
        return JwtUtil.createToken(user.getId(), username, CommonConstant.ADMIN_ISSUER, CommonConstant.ADMIN_TOKEN_EXPIRATION);
    }

    public void saveUser(User user, String passwordConfirm) {
        if (userRepository.existsByUsername(user.getUsername())) {
            throw new BaseException(Resp.ResStatus.PARAM_ERROR, "该用户名已存在");
        }
        if (!user.getPassword().equals(passwordConfirm)) {
            throw new BaseException(Resp.ResStatus.PARAM_ERROR, "密码与确认密码不一致");
        }
        if (!roleRepository.existsByIdAndDelFlag(user.getRoleId(),CommonConstant.NORMAL_FLAG)) {
            throw new BaseException(Resp.ResStatus.PARAM_ERROR, "该角色不存在");
        }
        user.setPassword(BCrypt.hashpw(user.getPassword()));
        save(user);
    }

    public void updateUser(User user){
        user.setPassword(null);
        user.setUsername(null);
        User u = userRepository.findOne(user.getId());
        if(u == null){
            throw new BaseException(Resp.ResStatus.PARAM_ERROR,"查无此用户");
        }
        //获取Hutool拷贝实例
        CopyOptions copyOptions = CopyOptions.create();
        //忽略为null值得属性
        copyOptions.setIgnoreNullValue(true);
        //进行属性拷贝
        BeanUtil.copyProperties(user, u, copyOptions);
        Set<String> ignoreProperties = new HashSet<>();
        ignoreProperties.add("username");
        ignoreProperties.add("password");
        BindingResult bindingResult = Validation.valid(u, ignoreProperties);
        if (!bindingResult.isFlag()) {
            throw new BaseException(Resp.ResStatus.PARAM_ERROR,bindingResult.getMessage().get(0));
        }
        save(u);
    }

    public void restPassword(String id){
        User u = userRepository.findOne(id);
        if(u == null){
            throw new BaseException(Resp.ResStatus.PARAM_ERROR,"查无此用户");
        }
        u.setPassword(BCrypt.hashpw("123456"));
        userRepository.save(u);
    }
}
